package com.example.audit.codesec_client.whitelistDemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.*;
import java.util.regex.Pattern;

public class ReturnDemo {
    @RequestMapping("/jdbc/vuln")
    public String jdbc_sqli_vul(@RequestParam("username") String username) {
        StringBuilder result = new StringBuilder();
        try {
            // 安全函数验证
            username = this.securityValidate(username);



            Connection con = DriverManager.getConnection("/test/sql", "username", "password");
            Statement statement = con.createStatement();
            String sql = "select * from users where username = '" + username + "'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                String res_name = rs.getString("username");
                String res_pwd = rs.getString("password");
                String info = String.format("%s: %s\n", res_name, res_pwd);
                result.append(info);
            }
            rs.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    // SQL安全过滤函数
    public String securityValidate(String sql) {
        Pattern FILTER_PATTERN = Pattern.compile("^[a-zA-Z0-9_/\\.-]+$");
        if (!FILTER_PATTERN.matcher(sql).matches()) {
            return null;
        }
        return sql;
    }
}
